<?php

namespace app\admin\controller\yunfood\order;

use addons\yunfood\library\Logic;
use addons\yunfood\model\Order;
use addons\yunfood\model\OrderItem;
use addons\yunfood\model\PrinterDevice;
use app\admin\model\yunfood\Order as OrderModel;
use app\admin\model\yunfood\Shop;
use app\admin\model\yunfood\ShopDesk;
use app\admin\model\yunfood\SysUser;
use addons\yunfood\library\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 订单
 */
class Main extends Backend
{
    /**
     * @var OrderModel
     */
    protected $model;

    // 联表查询，解决字段冲突
    protected $relationSearch = true;

    protected $noNeedRight = ['shopDesk'];

    protected $shopField = 'shop_id';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new OrderModel();

        // 就餐方式
        $this->view->assign('enjoyTypeList', $this->model::getEnjoyTypeList());
        $this->assignconfig('enjoyTypeList', $this->model::getEnjoyTypeList());

        // 支付状态
        $this->view->assign('paymentStatusList', $this->model::getPaymentStatusList());
        $this->assignconfig('paymentStatusList', $this->model::getPaymentStatusList());

        // 退款状态
        $this->view->assign('refundStatusList', $this->model::getRefundStatusList());
        $this->assignconfig('refundStatusList', $this->model::getRefundStatusList());

        // 开票状态
        $this->view->assign('invoiceStatusList', $this->model::getInoviceStatusList());
        $this->assignconfig('invoiceStatusList', $this->model::getInoviceStatusList());

        // 打印状态
        $this->view->assign('printStatusList', $this->model::getPrintStatusList());
        $this->assignconfig('printStatusList', $this->model::getPrintStatusList());

        // 状态
        $this->view->assign('statusList', $this->model::getStatusList());
        $this->assignconfig('statusList', $this->model::getStatusList());
    }

    /**
     * 查看
     */
    public function index()
    {
        $shopId = $this->request->request('shop_id');
        $deskId = $this->request->request('desk_id');
        if ($this->request->isAjax()) {
            // 转发到selectOrder
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            // 重载查询条件
            $filter = $this->request->get('filter');
            $op = $this->request->get('op');
            list($filter, $op) = $this->formatFilterOp($filter, $op);
            $this->request->get(['filter' => $filter, 'op' => $op]);

            // 通用查询条件
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            // 查询门店
            $where = $this->getShopWhere($where, 'order.shop_id');
            $query = $this->model->with(['shop_data', 'desk_data', 'user_data'])
                ->field('order.*')
                ->join([SysUser::getTableName() => 'user'], 'user.id=order.user_id', 'LEFT')
                ->where($where);
            if ($shopId) {
                $query->where(['order.shop_id' => $shopId]);
            }
            if ($deskId) {
                $query->where(['order.desk_id' => $deskId]);
            }
            $list = $query->order($sort, $order)->limit($offset, $limit)->paginate($limit);
            $result = array(
                'total' => $list->total(),
                'rows'  => $list->items(),
            );

            return json($result);
        }

        $this->view->assign('shopId', $shopId);
        $this->assignconfig('shopId', $shopId);
        $this->view->assign('deskId', $deskId);
        $this->assignconfig('deskId', $deskId);

        // 门店列表
        $shopList = Shop::getOptionList($this->getShopWhere(null, 'id'), true, false);
        $this->view->assign('shopList', $shopList);
        $this->assignconfig('shopList', $shopList);

        // 桌号列表
        $deskList = $shopId ? ShopDesk::getOptionList($shopId) : [];
        $this->view->assign('deskList', $deskList);
        $this->assignconfig('deskList', $deskList);

        return $this->view->fetch();
    }

    /**
     * 格式化查询条件
     *
     * @param $filter
     * @param $op
     * @return array
     */
    private function formatFilterOp($filter, $op)
    {
        $filter = json_decode($filter, true);
        $op = json_decode($op, true);

        return [json_encode($filter), json_encode($op)];
    }

    /**
     * 重新生成
     */
    public function print($ids = null)
    {
        $row = $this->model::get($ids);
        if (! $row) {
            $this->error(__('No Results were found'));
        }
        $this->authToShop($row['shop_id']);

        try {
            Logic::startPrint($row, PrinterDevice::SCENE_ORDER);
            $row->print_times++;
            $row->print_status = OrderModel::PRINT_STATUS_DOWN;
            $row->print_time = time();
            $row->save();
        } catch (\Throwable $e) {
            $this->error($e->getMessage());
        }

        $this->success();
    }

    /**
     * 联动搜索
     */
    public function shopDesk()
    {
        $group = $this->request->get('group');
        $shopId = $this->request->get('shop_id');

        $list = [];
        if ($group === 'shop') {
            foreach (Shop::getOptionList($this->getShopWhere(null, 'id')) as $key => $value) {
                $list[] = ['value' => $key, 'name' => $value];
            }
        } elseif ($group === 'desk') {
            $list = ShopDesk::field('id as value, number name')->where($this->getShopWhere())
                ->where('shop_id', $shopId)->select();
        }
        $this->success('', null, $list);
    }

    /**
     * 编辑
     */
    public function change($ids)
    {
        if (! $row = $this->model::get(['id' => $ids])) {
            $this->error(__('No Results were found'));
        }
        $this->authToShop($row['shop_id']);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($row->status != OrderModel::STATUS_WAIT_PAY) {
                    $this->error(__('当前订单状态不能执行此操作'));
                }
                if ($row->total_price < $params['payment']) {
                    $this->error(__('不能大于商品总价'));
                }
                if ($row->balance >= $params['payment']) {
                    $this->error(__('必须大于余额支付'));
                }
                if ($params['payment'] <= 0) {
                    $this->error(__('价格必须大于0'));
                }
                if ($row->payment == $params['payment']) {
                    $this->error(__('价格未变更'));
                }
                $result = false;
                Db::startTrans();
                try {
                    // 价格重新计算
                    if ($split = $row->payment - $params['payment']) {
                        $orderItems = $row->orderItemlistData;
                        OrderItem::scaleOrderItemPayment($orderItems, $split, $row->payment);
                        foreach ($orderItems as $item) {
                            $item->save();
                        }
                    }
                    $result = $row->save([
                        'payment'  => $params['payment'],
                        'discount' => $row->total_price - $params['payment']
                    ]);
                    Db::commit();
                } catch (ValidateException | PDOException | Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign('row', $row);

        return $this->view->fetch();
    }

    /**
     * 手动取消
     */
    public function manualCancel($ids)
    {
        if (! $row = $this->model::get($ids)) {
            $this->error(__('No Results were found'));
        }
        $this->authToShop($row['shop_id']);
        if ($row->status != OrderModel::STATUS_WAIT_PAY) {
            $this->error(__('当前订单状态不能执行此操作'));
        }

        // 取消订单
        try {
            Order::cancelOrder($row->order_no);
        } catch (Exception $e) {
            $this->error(__($e->getMessage()));
        }

        $this->success();
    }

    /**
     * 标记已支付
     */
    public function markPayed($ids)
    {
        if (! $row = $this->model::get($ids)) {
            $this->error(__('No Results were found'));
        }
        $this->authToShop($row['shop_id']);
        if ($row->status != OrderModel::STATUS_WAIT_PAY) {
            $this->error(__('当前订单状态不能执行此操作'));
        }
        OrderModel::finishOrder($row->order_no, $row->payment, '人工确认');

        $this->success();
    }

    /**
     * 标记已完成
     */
    public function markFinish($ids)
    {
        if (! $row = $this->model::get($ids)) {
            $this->error(__('No Results were found'));
        }
        $this->authToShop($row['shop_id']);
        if ($row->status != OrderModel::STATUS_WAIT_PAY) {
            $this->error(__('当前订单状态不能执行此操作'));
        }
        OrderModel::finishOrder($row->order_no, 0, '直接下单', OrderModel::PAYMENT_STATUS_IGNORE);

        $this->success();
    }

    public function recyclebin()
    {
        return;
    }

    public function destroy($ids = null)
    {
        return;
    }

    public function restore($ids = null)
    {
        return;
    }
}
